package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.safeguard.SafeguardConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {
    private static LambdaQueryWrapper queryWrapper(SafeguardVO safeguardVO) {
        //创建查询条件对象
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        if (safeguardVO != null) {

            /*if (StrUtil.isNotBlank(safeguardVO.getSafeguardKey())) {
                queryWrapper.eq(Safeguard::getSafeguardKey,safeguardVO.getSafeguardKey());
            }*/
            queryWrapper
                    //保障项编号
                    .eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                    //保障项名称
                    .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                    //状态
                    .eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState())
            ;
            //按照创建时间排序字段降序排序
            queryWrapper.orderByDesc(Safeguard::getCreateTime);
        }
        return queryWrapper;
    }

    //使用spring cache 缓存分页数据
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {

        LambdaQueryWrapper queryWrapper = queryWrapper(safeguardVO);

        Page<Safeguard> safeguardPage = page(new Page<>(pageNum, pageSize), queryWrapper);
        return BeanConv.toPage(safeguardPage, SafeguardVO.class);
    }
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardId")
    @Override
    public SafeguardVO findById(String safeguardId) {
        try {
            //1、查询数据
            Safeguard safeguard = getById(safeguardId);
            if (BeanUtil.isEmpty(safeguard)) {
                return null;
            }
            //2、将PO转换成VO
            return BeanConv.toBean(safeguard, SafeguardVO.class);
        } catch (Exception e) {
            log.error("查询保险保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }

    @Caching(evict =
            {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)},
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id")}
    )
    @Override
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try {
            //1、将VO对象转换成PO
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //2、保存数据
            boolean flag = save(safeguard);
            if (!flag) {
                throw new RuntimeException("保存保障项失败");
            }
            //3、返回操作结果
            return BeanConv.toBean(safeguard, SafeguardVO.class);
        } catch (Exception e) {
            log.error("保存保险保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    @Caching(evict =
            {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)},
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id")}
    )
    @Override
    public Boolean update(SafeguardVO safeguardVO) {
        try {
            //1、将VO对象转换成PO
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //2、根据id更新数据
            boolean flag = updateById(safeguard);
            if (!flag) {
                throw new RuntimeException("修改保障项失败");
            }
            //3、返回操作结果
            return flag;
        } catch (Exception e) {
            log.error("修改保险保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    @Caching(evict = {
            @CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)}
    )
    @Override
    public Boolean delete(String[] checkedIds) {
        try {
            //1、将数组转换为元素类型为Long的集合
            List<Long> ids = Arrays.stream(checkedIds).map(Long::valueOf).collect(Collectors.toList());
            //2、删除数据
            boolean flag = removeByIds(ids);
            if (!flag) {
                throw new RuntimeException("删除保障项失败");
            }
            //3、返回操作结果
            return flag;
        } catch (Exception e) {
            log.error("删除保险保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#safeguardVO.hashCode()")
    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            LambdaQueryWrapper queryWrapper = queryWrapper(safeguardVO);
            List<Safeguard> safeguardList = list(queryWrapper);
            if (safeguardList != null) {
                return BeanConv.toBeanList(safeguardList, SafeguardVO.class);
            }
        } catch (Exception e) {
            log.error("查询保险保障项列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
        return List.of();
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        return List.of();
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        return null;
    }
}
